from rest_framework import status
from rest_framework.decorators import api_view
from .serializers import *
from rest_framework.response import Response
from django.core.mail import send_mail
from django.conf import settings
from django.core import signing
from rest_framework_jwt.settings import api_settings
from djangoProject.settings import DEFAULT_URL


@api_view(['POST', ])
def register(request):
    new_username = request.data['username']
    new_password = request.data['password']

    if User.objects.filter(username=new_username).count() != 0:
        response = {'msg': '用户已存在'}
        return Response(response, status=status.HTTP_200_OK)
    else:
        User.objects.create(username=new_username, password=new_password)
        response = {'msg': '注册成功'}
        return Response(response)


@api_view(['POST', ])
def login(request):
    username = request.data['username']
    password = request.data['password']
    if User.objects.filter(username=username).count() == 0:
        response = {'msg': '用户不存在', 'status': 403}
        return Response(response, status=status.HTTP_200_OK)
    user = User.objects.get(username=username)
    if password == user.password:
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        response = {'msg': '登录成功', 'token': token, 'status': 200}
        return Response(response, status=status.HTTP_200_OK)
    else:
        response = {'msg': '密码错误', 'status': 401}
        return Response(response, status=status.HTTP_200_OK)


@api_view(['POST', ])
def upload_avatar(request):
    print(request.data)
    image = request.data.get('image', None)
    username = request.data.get('username')
    user = User.objects.get(username=username)
    try:
        user.avatar = image
    except:
        return Response(status=status.HTTP_400_BAD_REQUEST)
    else:
        user.save()
        url = DEFAULT_URL[:-1] +user.avatar.url
        response = {'msg': url}
        return Response(response)


@api_view(['POST', ])
def find_password(request):
    username = request.data.get('username')
    if User.objects.filter(username=username).count() == 0:
        response = {'msg': '用户不存在'}
        return Response(response)
    else:
        user = User.objects.get(username=username)
        email = user.email

        value = signing.dumps({"username": user.username})
        link = 'localhost:8080/resetpassword/' + value
        msg = '请点击此链接重置密码' + '<a href="' + link + '">' + link + '</a>'
        send_mail(subject='找回密码',
                  message='this is message',
                  html_message=msg,
                  from_email=settings.EMAIL_HOST_USER,
                  recipient_list=[email],
                  fail_silently=False, )
        return Response()


@api_view(['POST', ])
def resetPassword(request):
    username = request.data.get('username')
    user = User.objects.get(username=username)
    user.password = request.data.get('password')
    user.save()
    return Response(status=status.HTTP_200_OK)


@api_view(['POST', ])
def decode(request):
    code = request.data.get('username')
    value = signing.loads(code)
    response = {'msg': value["username"]}
    return Response(response, status=status.HTTP_200_OK)


@api_view(['POST', ])
def user_info(request):
    username = request.data.get('username')
    user = User.objects.get(username=username)
    response = {
        'username': username,
        'url': DEFAULT_URL[:-1] + user.avatar.url
    }
    return Response(response, status=status.HTTP_200_OK)
